package event

import (
	"sync"
)

// Event represents a basic event structure.

// EventHandler is a function type for handling events.
type EventHandler func(eventData ...interface{})

// EventEmitter represents an event emitter.
type EventEmitter struct {
	mutex    sync.Mutex
	eventMap map[string][]EventHandler
}

// NewEventEmitter creates a new EventEmitter.
func NewEventEmitter() *EventEmitter {
	return &EventEmitter{
		eventMap: make(map[string][]EventHandler),
	}
}

// On registers an event handler for a specific event.
func (e *EventEmitter) On(eventID string, handler EventHandler) {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	// Check if the handler is already registered for the event
	for _, existingHandler := range e.eventMap[eventID] {
		if existingHandler != nil {
			return // Handler is already registered, do nothing
		}
	}

	if _, exists := e.eventMap[eventID]; !exists {
		e.eventMap[eventID] = make([]EventHandler, 0)
	}

	e.eventMap[eventID] = append(e.eventMap[eventID], handler)
}

// Off removes an event handler for a specific event.
func (e *EventEmitter) Off(eventID string) {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	if _, exists := e.eventMap[eventID]; exists {
		delete(e.eventMap, eventID)
	}
}

// Emit dispatches an event with the given name and data to all registered handlers.
func (e *EventEmitter) Emit(eventID string, data ...interface{}) {
	// e.mutex.Lock()
	// defer e.mutex.Unlock()

	if handlers, exists := e.eventMap[eventID]; exists {
		for _, handler := range handlers {
			handler(data...)
		}
	}
}
